// Copyright (c) MatrixFramework. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using MatrixFramework.Keycloak.Abstractions.Models;
using MatrixFramework.Keycloak.Abstractions.Options;
using MatrixFramework.Keycloak.Abstractions.Services;

namespace MatrixFramework.Keycloak.Services;

/// <summary>
/// 默认租户服务
/// </summary>
public class TenantService : ITenantService
{
    private readonly IKeycloakAdminService _keycloakAdminService;
    private readonly IOptionsMonitor<KeycloakOptions> _options;

    public TenantService(
        IKeycloakAdminService keycloakAdminService,
        IOptionsMonitor<KeycloakOptions> options)
    {
        _keycloakAdminService = keycloakAdminService;
        _options = options;
    }

    public Task<string> GetTenantRealmAsync(string tenantId)
    {
        var multiTenantOptions = _options.CurrentValue.MultiTenant;
        var realmName = multiTenantOptions.RealmNaming switch
        {
            RealmNamingStrategy.TenantId => tenantId,
            RealmNamingStrategy.TenantName => tenantId, // TODO: 从存储获取租户名称
            RealmNamingStrategy.TenantCode => tenantId, // TODO: 从存储获取租户代码
            RealmNamingStrategy.CustomPrefix => $"{multiTenantOptions.TenantPrefix}{tenantId}",
            _ => multiTenantOptions.DefaultRealmTemplate.Replace("{tenant-id}", tenantId, StringComparison.OrdinalIgnoreCase)
        };

        return Task.FromResult(realmName);
    }

    public async Task<bool> CreateTenantRealmAsync(string tenantId, string tenantName)
    {
        var realmName = await GetTenantRealmAsync(tenantId);

        var realmInfo = new RealmCreationInfo
        {
            RealmName = realmName,
            DisplayName = tenantName,
            Description = $"租户 {tenantName} 的专用Realm"
        };

        var result = await _keycloakAdminService.CreateRealmAsync(realmInfo);
        return result.IsSuccess;
    }
}